<template>
  <div class="schedule-table">
    <!-- 日程表格 -->
    <el-table
      v-loading="listLoading"
      :data="disposeFormListViewTime(tableData, columns)"
      header-row-class-name="common-list-table-header__v2"
      :class="['bbx-normal-list-box']"
      stripe
      border
      max-height="500"
    >
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>
      <el-table-column
        v-for="column in columns"
        :key="column.id"
        :prop="column.field"
        :label="column.displayName"
        :fixed="column.isFixed"
        :width="column.width"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <template v-if="column.field === 'calendarName'">
            <span class="link" @click="handleViewSchedule(row)">{{
              row.calendarName || ''
            }}</span>
          </template>
          <template v-else-if="column.field === 'userList'">
            {{ row.userList | tagName }}
          </template>
          <template v-else-if="column.field == 'startTime' || column.field == 'endTime'">
           {{ row[column.field] | fmt_datetime}}
          </template>
          <template v-else-if="column.field == 'operation'">
            <span class="edit-btn pub-btn" @click="handleViewSchedule(row)"
              >{{$t('contract.scheduleTable.viewSchedule')}}</span
            >
            <span
              v-if="row.editAuth"
              @click="handleEdit(row)"
              class="edit-btn pub-btn mar-l-10"
              >{{$t('common.base.edit')}}</span
            >
            <span
              v-if="row.deleteAuth"
              @click="handleDel(row)"
              class="mar-l-10 del-btn pub-btn"
              >{{$t('common.base.delete')}}</span
            >
          </template>
          <template v-else>
            {{ row[column.field] }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="tableData.length" class="table-footer">

      <i18n path="common.base.table.totalCount">
        <span place="count" class="level-padding">{{ page.total }}</span>
      </i18n>

      <el-pagination
        background
        @current-change="handleCurrentChange"
        :page-size="page.pageSize"
        :current-page="page.pageNum"
        layout="prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import {
  ref,
  onMounted,
  reactive,
  toRefs,
  computed,
} from 'vue';

// import Platform from '@src/util/platform.ts';
import platform from '@src/platform';
import { MessageBox } from 'element-ui';
import i18n from '@src/locales';

// api
import { getCalendarListView } from '@src/api/ContractApi';
import { deleteAgenda } from '@src/api/CalendarApi.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab, toast } from '@src/util/platform'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()
export default {
  props: {},
  filters: {
    tagName(value) {
      if (!value || !Array.isArray(value) || !value.length) return '';

      return value
        .filter(item => item && item.displayName)
        .map(item => item.displayName)
        .join('，');
    },
  },
  setup() {
    const columns = ref([
      {
        id: 1,
        displayName: i18n.t('contract.scheduleTable.columns.orderNo'),
        field: 'orderNo',
      },
      {
        id: 2,
        displayName: i18n.t('contract.scheduleTable.columns.calendarName'),
        field: 'calendarName',
      },
      {
        id: 3,
        displayName: i18n.t('contract.scheduleTable.columns.desc'),
        field: 'desc',
      },
      {
        id: 4,
        displayName: i18n.t('contract.scheduleTable.columns.startTime'),
        field: 'startTime',
      },
      {
        id: 5,
        displayName: i18n.t('contract.scheduleTable.columns.endTime'),
        field: 'endTime',
      },
      {
        id: 6,
        displayName: i18n.t('contract.scheduleTable.columns.userList'),
        field: 'userList',
      },
      {
        id: 7,
        displayName: i18n.t('contract.scheduleTable.columns.calendarRemind'),
        field: 'calendarRemind',
      },
      {
        id: 8,
        displayName: i18n.t('contract.scheduleTable.columns.repeatTypeStr'),
        field: 'repeatTypeStr',
      },
      {
        id: 9,
        displayName: i18n.t('contract.scheduleTable.columns.action'),
        field: 'operation',
        isFixed: 'right',
        width: '160',
      },
    ]);

    const state = reactive({
      tableData: [],
      listLoading: false,
      page: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
    });

    // 合同id
    const contractId = computed(() => {
      return location.pathname.split('/contract/view/')[1] || '';
    });

    // 查看日程
    const handleViewSchedule = val => {
      const { id, startTime, endTime } = val;
      const startDate = new Date(startTime).getTime();
      const endDate = new Date(endTime).getTime();

      let fromId = window.frameElement.getAttribute('id');
      // platform.openTab({
      //   id: `schedule`,
      //   title: '日程管理',
      //   url: `/calendar?id=${id}&startTime=${startDate}&endTime=${endDate}`,
      //   close: true,
      //   reload: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSchedule,
        reload: true,
        params: `id=${id}&startTime=${startDate}&endTime=${endDate}`,
        fromId
      })
    };

    // 编辑
    const handleEdit = val => {
      let fromId = window.frameElement.getAttribute('id');
      // platform.openTab({
      //   id: `schedule`,
      //   title: '日程管理',
      //   url: `/calendar?type=edit&calendarId=${val.id}&contractId=${contractId.value}`,
      //   close: true,
      //   reload: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSchedule,
        reload: true,
        params: `type=edit&calendarId=${val.id}&contractId=${contractId.value}`,
        fromId
      })
    };

    // 删除
    const handleDel = val => {
      MessageBox.confirm(i18n.t('contract.scheduleTable.delConfirmMsg'), i18n.t('common.base.toast'), {
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            deleteAgenda({ agendaId: val.id, deleteTime: val.startTime }).then(
              res => {
                instance.confirmButtonLoading = false;
                if (res.status != 0) {
                  return platform.notification({
                    title: res.message,
                    type: 'error',
                  });
                }
                platform.notification({
                  title: i18n.t('common.base.deleteSuccess'),
                  type: 'success',
                });

                handleCurrentChange(1);
                done();
              }
            );
          } else {
            done();
          }
        },
      });
    };

    // 页数改变时触发
    const handleCurrentChange = pageNum => {
      state.page.pageNum = pageNum;
      getCalendarList();
    };

    // 获取列表数据
    const getCalendarList = async () => {
      state.listLoading = true;
      state.tableData = [];

      try {
        let res = await getCalendarListView({
          contractId: contractId.value,
          ...state.page,
        });

        if (!res.success) return toast(res.message, 'error');

        let { list, total } = res.result;

        state.tableData = list;
        state.page.total = total;
      } catch (error) {
        console.log('error=>', error);
      } finally {
        state.listLoading = false;
      }
    };

    onMounted(() => {
      getCalendarList()
    });

    return {
      columns,
      handleViewSchedule,
      handleEdit,
      handleDel,
      handleCurrentChange,
      ...toRefs(state),
      getCalendarList,
      disposeFormListViewTime
    };
  },
};
</script>
<style lang="scss" scoped>
@import './Statistics.scss';

.schedule-table {
  height: calc(100% - 108px);
  overflow-y: auto;
  padding: 0 16px;
}
</style>